#Get objects
old_ws = ls()

########################
#Tables Violence: PODES#
########################

useTable_podes = mergedTable_podes[!is.na(Violence_1_count) & (sample_ni_it)]

#Model specifications
nb_specs = expand.grid(x = 'IT_win', 
                       y = c(paste0('Violence_',1,'_count'),
                             paste0('Violence_',1,'_deaths')), stringsAsFactors = F
)

lm_specs = expand.grid(x = 'IT_win', 
                       y = c(paste0('Violence_',1,'_binary'), 
                             paste0('Violence_',1,'_deaths_binary')), stringsAsFactors = F
)

#############
#NVMS sample#
#############

#Estimate models
nb_models = Map(function(y,x) glmnb_loop(y,x, useTable_podes[(nvms_sample)]),
                nb_specs$y, nb_specs$x)

lm_models = Map(function(y,x) lm_loop(y,x,  useTable_podes[(nvms_sample)]),
                lm_specs$y, lm_specs$x)


#Get clustered standard errors
table_list = c(nb_models, lm_models)
table_se = lapply(table_list, function(x) cluster_errors(x, useTable_podes[(nvms_sample), cluster]) %>% diag %>% sqrt)

#create table
n_clusters = useTable_podes[(nvms_sample), cluster] %>% unique %>% length
note_text = paste("Standard errors clustered by", n_clusters, "constituency-clusters. Observations are constituencies in which the last seat was contested by Islamist and secular parties with a margin less than 1 percent.")

table = stargazer(table_list, se = table_se, type = 'latex', 
          title = "Effects of Islamist Victory on Religious Violence (PODES)---NVMS Sample",
          #out = './output/tables/podes_violence_nvms_ni_it.tex',
          label = 'tab:podes_violence_nvms_ni_it',
          model.names = F,
          model.numbers = F,
          column.separate = c(4),
          dep.var.labels = rep(c("Events","Deaths"), 2), 
          add.lines = list(c('Count', rep(c('Y', 'Y', 'N', 'N'), 1)),
                           c('Binary', rep(c('N', 'N', 'Y', 'Y'), 1))),
          covariate.labels = c("Islamist Win"),
          star.cutoffs = c(0.1, 0.05, 0.01),
          #float.env = 'sidewaystable',
          notes.align = 'l',
          keep.stat = 'n')


write_latex(table[-10] %>% append(table[10], after = 10) %>% append("\\cmidrule(lr){2-5}", after = 10), note_text, './output/tables/table_e5.tex')

#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)